package middleware

import (
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"io/ioutil"
	"net/http"
)

type JWTClaims struct {
	jwt.StandardClaims
	UserID int `json:"user_id"`
	Password string	`json:"password"`
	Username string `json:"username"`
	IssueAt    int64   `json:"issueAt"`
	ExpiresAt    int64   `json:"expiresAt"`
	Permission []string `json:"permission"`
}

var (
	hmacSampleSecret []byte
	ExpireTime = 3600*24
)

func init(){
	if keyData,err := ioutil.ReadFile("app.rsa");err==nil{
		hmacSampleSecret = keyData
	}else{
		panic(err)
	}
}

//生成token
func CreateToken(claims *JWTClaims)(signedToken string,err error){
	token := jwt.NewWithClaims(jwt.SigningMethodHS256,claims)
	signedToken,err = token.SignedString([]byte(hmacSampleSecret))
	if err != nil{
		return "",err
	}
	return signedToken,nil
}

//验证token是否生效
func Verify() gin.HandlerFunc{
	return func(c *gin.Context){
		_,err := verifyAction(c.GetHeader("Authorization"))
		if err!=nil{
			c.AbortWithStatus(http.StatusUnauthorized)
		}
		c.Next()
	}
}

//验证用户信息
func verifyAction(strToken string)(claims *JWTClaims,err error){
	token,err := jwt.ParseWithClaims(strToken,&JWTClaims{},func(token *jwt.Token)(interface{},error){
		return []byte(hmacSampleSecret),nil;
	})
	if err != nil{
		return nil,err
	}
	claims,ok := token.Claims.(*JWTClaims)
	if !ok{
		return nil,err
	}
	if err := token.Claims.Valid();err != nil{
		return nil,err
	}
	return claims,nil
}
